package com.moleq.mgpos.activities;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import android.R.integer;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.inputmethodservice.Keyboard;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.moleq.adapter.NetworkAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.dialog.GlobalPriceChangeDialog2;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.NetworkListsDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.models.GlobalInfo;
import com.moleq.models.NetworkSetting;
import com.moleq.network.CommunicationCallback;
import com.moleq.network.ConnectHandler;
import com.moleq.service.NetWorkSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.util.MoleQUtil;

public class NetworkSettingActivity extends MoleQBaseActivity {
	/** Called when the activity is first created. */

	private BeepImageButton iv_net_add, iv_net_del, iv_net_ok, iv_net_refresh, iv_net_ping;
	private ListView lv_netlist;
	private EditText et_net_station_no, et_net_name, et_net_ip;
	private List<NetworkSetting> mNetworkSettingLst;
	private NetworkSetting mCurrentItem;
	private NetWorkSettingService mNetService;
	private NetworkAdapter mNetWorkAdapter;
	private Button btn_exit;
	private AbsoluteLayout al_net_detail;
	private LinearLayout ll_net;
	private String mloaclIpAddress = "";
	public int NetWorkmode = 0;
	private NetworkListsDialog mNetworkListsDialog = null;
	private WifiManager wifi_service = null;
	private ConnectHandler mNetworkMonitor = null;
	private CommunicationCallback mCmmCallback = new CommunicationCallback() {

		@Override
		public void onError(String errMsg) {
			// TODO Auto-generated method stub
			Log.e("networksetting", " error message -> " + errMsg);
			// handler.sendMessage(handler.obtainMessage(0, ""));
		}

		@Override
		public void onConnected(String ip) {

			Log.i("networksetting", ip + " is connected...");
			setOnlineIpAddress(ip);

		}

		@Override
		public void onCheckNetworkStart() {
			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(1, ""));
		}

		@Override
		public void onCheckNetworkComplete() {
			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(0, ""));

			mNetworkhandler.sendMessage(mNetworkhandler.obtainMessage(3, ""));

		}

		@Override
		public void onDisconnected(String ip) {
			Log.i("networksetting", ip + " is disconnected...");

		}
	};

	private void setOnlineIpAddress(String ip) {
		if (mNetworkSettingLst != null && mNetworkSettingLst.size() > 0) {

			for (int i = 0; i < mNetworkSettingLst.size(); i++) {
				if (ip.endsWith(mNetworkSettingLst.get(i).getNs_ip())) {
					mNetworkSettingLst.get(i).setOnline(true);
					// mNetworkSettingLst.get(i).setNs_name("on line0");
					Log.i("networksetting", " check ip -> " + mNetworkSettingLst.get(i).getNs_ip());
					break;
				}
			}

		}
	}
	
	private void resetIpAddres(){
		if (mNetworkSettingLst != null && mNetworkSettingLst.size() > 0) {

			for (int i = 0; i < mNetworkSettingLst.size(); i++) {
				mNetworkSettingLst.get(i).setOnline(false);
			}
			
			mNetWorkAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_network_setting);
		
		getcontrols();

		mNetService = ServiceManager.getInstance().mNetWorkSettingService;

		mNetworkSettingLst = mNetService.FindAll();
		if (mNetWorkAdapter == null)
			mNetWorkAdapter = new NetworkAdapter(this, mNetworkSettingLst);
		lv_netlist.setAdapter(mNetWorkAdapter);
		if (mNetworkSettingLst.size() > 0) {
			showItemInfo( mNetworkSettingLst.get(0));
			mNetWorkAdapter.ScrollToRow(0);
		}
		SetEnabledTrue();
		wifi_service = (WifiManager) getSystemService(WIFI_SERVICE);
		if (wifi_service!= null && wifi_service.isWifiEnabled()) {
			mloaclIpAddress = getWifiLocalIpAddress();
		}else {
			mloaclIpAddress = getLocalIpAddress();
		}
		if (mNetworkSettingLst != null && mNetworkSettingLst.size() > 0) {
			for (int i = 0; i < mNetworkSettingLst.size(); i++) {
				if(mNetworkSettingLst.get(i).getNs_ip().equals(mloaclIpAddress)){
					mNetworkSettingLst.get(i).setLocal(true);
				}
			}
		}

		mNetworkMonitor = new ConnectHandler(6677, mCmmCallback);
		

	}

	private void getcontrols() {
		// TODO Auto-generated method stub
		iv_net_add = (BeepImageButton) findViewById(R.id.iv_net_add);
		iv_net_add.setOnClickListener(onImageClickListener);
		iv_net_del = (BeepImageButton) findViewById(R.id.iv_net_del);
		iv_net_del.setOnClickListener(onImageClickListener);
		iv_net_ok = (BeepImageButton) findViewById(R.id.iv_net_ok);
		iv_net_ok.setOnClickListener(onImageClickListener);
		iv_net_refresh = (BeepImageButton) findViewById(R.id.iv_net_refresh);
		iv_net_refresh.setOnClickListener(onImageClickListener);
		iv_net_ping = (BeepImageButton) findViewById(R.id.iv_net_ping);
		iv_net_ping.setOnClickListener(onImageClickListener);

		btn_exit = (Button) findViewById(R.id.btn_net_exit);
		btn_exit.setOnClickListener(onClickListener);

		lv_netlist = (ListView) findViewById(R.id.lv_netlist);
		lv_netlist.setOnItemClickListener(onItemClickListener);

		et_net_station_no = (EditText) findViewById(R.id.et_net_station_no);
		et_net_station_no.addTextChangedListener(watcher);
		et_net_name = (EditText) findViewById(R.id.et_net_name);
		et_net_name.addTextChangedListener(watcher);
		et_net_ip = (EditText) findViewById(R.id.et_net_ip);
		et_net_ip.addTextChangedListener(watcher);

		al_net_detail = (AbsoluteLayout) findViewById(R.id.al_net_detail);
		al_net_detail.setOnClickListener(onClickListener);
		ll_net = (LinearLayout) findViewById(R.id.ll_net);
		ll_net.setOnClickListener(onClickListener);
	}

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			mCurrentItem = mNetworkSettingLst.get(position);
			showItemInfo(mCurrentItem,position);
//			if (position - 1 >= 0) {
//				mNetWorkAdapter.ScrollToRow(position);
//			}
			showKeyboard();
		}
	};

	public OnClickListener onClickListener = new OnClickListener() {

		public void onClick(View view) {

			switch (view.getId()) {
			case R.id.al_net_detail:
				showKeyboard();
				break;
			case R.id.ll_net:
				showKeyboard();
				break;
			case R.id.btn_net_exit:
				MessageBox.show(NetworkSettingActivity.this, NetworkSettingActivity.this.getResources().getString(R.string.msg_exit_program), confirmExitListener, MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			}
		}
	};

	private TextWatcher watcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
		}

		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			// TODO Auto-generated method stub
		}

		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if (NetWorkmode == 1 && mNetworkSettingLst.size() > 0) {
				SetEnabledFalse();// Fasle
			}
		}
	};

	private Handler mNetworkhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				Log.i("networksetting", " dismiss processing dialog -> ");
				if (mProcessingDlg != null || mProcessingDlg.isShowing()) {
					mProcessingDlg.dismiss();
				}
				break;
			case 1:
				Log.i("networksetting", " open processing dialog -> ");
				mProcessingDlg = new ProgressDialog(NetworkSettingActivity.this);
				mProcessingDlg.setTitle("");
				mProcessingDlg.setMessage("Scanning terminal, Please wait..");
				mProcessingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				mProcessingDlg.getWindow().setWindowAnimations(android.R.style.Animation);
				mProcessingDlg.show();
				break;
			case 3:
				mNetWorkAdapter.notifyDataSetChanged();
				break;

			default:
				break;
			}
		}
	};

	private ProgressDialog mProcessingDlg;
	public OnClickListener onImageClickListener = new OnClickListener() {

		public void onClick(View v) {
			int index = -1;
			switch (v.getId()) {
			case R.id.iv_net_add:
				mCurrentItem = new NetworkSetting();
				mCurrentItem.setNs_no(-1);
				mCurrentItem.setNs_name("");
				mCurrentItem.setNs_ip("");
				mNetworkSettingLst.add(mCurrentItem);

				showItemInfo(mCurrentItem);

				index = mNetworkSettingLst.size() - 1;
				mNetWorkAdapter.ScrollToRow(index);

				SetEnabledFalse();
				et_net_station_no.requestFocus();
				break;
			case R.id.iv_net_del:
				if (mNetworkSettingLst.size() <= 0) {
					return;
				}
				MessageBox.show(NetworkSettingActivity.this, "Do you want to delete the network setting?", comfirmDeleteListener, MessageDialog.MESSAGE_BOX_YES_NO);
				break;
			case R.id.iv_net_ok:
				mCurrentItem = mNetWorkAdapter.getSelectItem();
				if (!validation()){
					return;
				}

				String ip,
				name;
				int station_no;

				ip = et_net_ip.getText().toString();
				name = et_net_name.getText().toString();
				station_no = Integer.valueOf(et_net_station_no.getText().toString());

				mCurrentItem.setNs_ip(ip);
				mCurrentItem.setNs_station(station_no);
				mCurrentItem.setNs_name(name);

				if (mNetService.save(mCurrentItem)) {
					Toast.makeText(NetworkSettingActivity.this, "Save completed.", Toast.LENGTH_SHORT).show();
//					doNetWork();
					SetEnabledTrue();
					mNetWorkAdapter.notifyDataSetChanged();
					showKeyboard();
				}

				break;
			case R.id.iv_net_refresh:

				Log.i("networksetting", " check network..... ");

				resetIpAddres();
				
				new Thread() {
					public void run() {
						mNetworkMonitor.checkIpAddress(getIpList());
					};
				}.start();

				break;
			case R.id.iv_net_ping:
				if(mNetworkListsDialog == null){
					mNetworkListsDialog = new NetworkListsDialog(NetworkSettingActivity.this,NetworkSettingActivity.this,wifi_service);
					mNetworkListsDialog.show();
				}else{
					if (mNetworkListsDialog.isShowing()) {
						mNetworkListsDialog.dismiss();
					}
					mNetworkListsDialog = new NetworkListsDialog(NetworkSettingActivity.this,NetworkSettingActivity.this,wifi_service);
					mNetworkListsDialog.show();
				}
				
				break;
			default:
				// Keyboard();
				break;
			}
		}
	};

	public List<String> getIpList() {
		List<String> ips = new ArrayList<String>();
		if (mNetworkSettingLst != null && mNetworkSettingLst.size() > 0) {
			for (int i = 0; i < mNetworkSettingLst.size(); i++) {
				String ipAddress = mNetworkSettingLst.get(i).getNs_ip();
				if (!ipAddress.equals(mloaclIpAddress)) {
					ips.add(ipAddress);
				}
			}
		}
		return ips;
	}

	public void showItemInfo(NetworkSetting item) {
			NetWorkmode = 0;
			et_net_station_no.setText(item.getStation());
			et_net_name.setText(item.getNs_name());
			et_net_ip.setText(item.getNs_ip());
			NetWorkmode = 1;
	}
	
	public void showItemInfo(NetworkSetting item,int position) {
		if (mNetService.Find(item.getNs_no()) != null) {
			NetWorkmode = 0;
			et_net_station_no.setText(item.getStation());
			et_net_name.setText(item.getNs_name());
			et_net_ip.setText(item.getNs_ip());
			NetWorkmode = 1;
			mNetWorkAdapter.ScrollToRow(position);
		}else{
			mNetworkSettingLst = mNetService.FindAll();
			mNetWorkAdapter.setSource(mNetworkSettingLst);
			mNetWorkAdapter.notifyDataSetChanged();
			if(position - 1 >= 0){
				mNetWorkAdapter.ScrollToRow(position - 1);
				NetWorkmode = 0;
				et_net_station_no.setText(mNetworkSettingLst.get(position - 1).getStation());
				et_net_name.setText(mNetworkSettingLst.get(position - 1).getNs_name());
				et_net_ip.setText(mNetworkSettingLst.get(position - 1).getNs_ip());
				NetWorkmode = 1;
			}
		}
		
	}

	public boolean validation() {
		String ip, name, station_no, id;
		int index = -1 ;
		id = String.valueOf(mCurrentItem.getNs_no());
		station_no = et_net_station_no.getText().toString();
		ip = et_net_ip.getText().toString();
		name = et_net_name.getText().toString();

		if (station_no.equals("") && ip.equals("") && name.equals("")) {
			if (mCurrentItem.getNs_no() == -1) {
				mNetworkSettingLst.remove(mCurrentItem);
			}
			index = mNetworkSettingLst.size() - 1;
			if (index >= 0) {
				mNetWorkAdapter.ScrollToRow(mNetworkSettingLst.size() - 1);
				showItemInfo(mNetWorkAdapter.getSelectItem());
			}else{
				mNetWorkAdapter.notifyDataSetChanged();
			}

			SetEnabledTrue();
			return false;
		}
		
		if (station_no.equals("")) {
			MessageBox.show(NetworkSettingActivity.this, "Station # cannot be empty.");
			return false;
		}

		if (mNetService.checkStation(station_no, id)) {
			MessageBox.show(NetworkSettingActivity.this, "Station # cannot be duplicated.");
			return false;
		}

		if (name.equals("")) {
			MessageBox.show(NetworkSettingActivity.this, "Name cannot be empty.");
			return false;
		}

		if (ip.equals("")) {
			MessageBox.show(NetworkSettingActivity.this, "Ip address cannot be empty.");
			return false;
		}

		if (mNetService.checkIp(ip, id)) {
			MessageBox.show(NetworkSettingActivity.this, "IP cannot be duplicated.");
			return false;
		}

		if (!MoleQUtil.checkIp(ip)) {
			MessageBox.show(NetworkSettingActivity.this, "Ip address is not valid.");
			return false;
		}
		
		return true;
	}

	public void SetEnabledFalse() {
		iv_net_ping.setVisibility(View.INVISIBLE);
		iv_net_ok.setVisibility(View.VISIBLE);
		iv_net_add.setVisibility(View.INVISIBLE);
		iv_net_del.setVisibility(View.INVISIBLE);
		et_net_station_no.setEnabled(true);
		et_net_name.setEnabled(true);
		et_net_ip.setEnabled(true);
		lv_netlist.setEnabled(false);
		btn_exit.setEnabled(false);
	}
	
	public void SetEnabledFalse2() {
		iv_net_ok.setVisibility(View.INVISIBLE);
		iv_net_add.setVisibility(View.VISIBLE);
		iv_net_del.setVisibility(View.VISIBLE);
		et_net_station_no.setEnabled(true);
		et_net_name.setEnabled(true);
		et_net_ip.setEnabled(true);
		lv_netlist.setEnabled(true);
		btn_exit.setEnabled(true);
	}

	public void SetEnabledTrue() {
		if (mNetworkSettingLst.size() <= 0) {	
			et_net_station_no.setText("");
			et_net_name.setText("");
			et_net_ip.setText("");
			et_net_station_no.setEnabled(false);
			et_net_name.setEnabled(false);
			et_net_ip.setEnabled(false);
			
		} else {
			et_net_station_no.setEnabled(true);
			et_net_name.setEnabled(true);
			et_net_ip.setEnabled(true);
		}
		iv_net_ok.setVisibility(View.INVISIBLE);
		iv_net_add.setVisibility(View.VISIBLE);
		iv_net_del.setVisibility(View.VISIBLE);
		iv_net_ping.setVisibility(View.VISIBLE);
		lv_netlist.setEnabled(true);
		btn_exit.setEnabled(true);
	}

	public void showKeyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(NetworkSettingActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public String getWifiLocalIpAddress() {
		String wifilocalIpAddress = null;
		
		WifiInfo wifiinfo = wifi_service.getConnectionInfo();
		wifilocalIpAddress =  Formatter.formatIpAddress(wifiinfo.getIpAddress());
		
		return wifilocalIpAddress;
	}
	
	public String getLocalIpAddress() {
		String localIpAddress = null;
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						localIpAddress = inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		
		return localIpAddress;
	}

	private void dispose() {
		// TODO Auto-generated method stub
		if (mNetworkMonitor != null) {
			mNetworkMonitor.release();
		}

	}
	
//	public void doNetWork(){
//		
//		if (GlobalInfo.getInstance().isMGNetwork) {
//			
//			List<NetworkSetting> mNsl =  mNetService.FindAll();
//			mMGCreateFiles.createrFile(mCurrentItem.toMGData("DELETE"));//UPDATE,DELETE
//			
//			for (int i = 0; i <mNsl.size(); i++) {
//				mMGCreateFiles.createrFile(mNetworkSettingLst.get(i).toMGData("UPDATE"));//UPDATE,DELETE
//			}
//		}
//	}

	private OnClickMessageListener comfirmDeleteListener = new OnClickMessageListener() {
		@Override
		public void onClickYes() {
			mCurrentItem = mNetWorkAdapter.getSelectItem();
			if (mNetService.Delete(mCurrentItem.getNs_no())) {
//				if (GlobalInfo.getInstance().isMGNetwork) {
//					mMGCreateFiles.createrFile(mCurrentItem.toMGData("DELETE"));//UPDATE,DELETE
//				}
//				doNetWork();
				mNetworkSettingLst.remove(mCurrentItem);
				int index = mNetworkSettingLst.size() - 1;
				if (index >= 0 ) {
					mNetWorkAdapter.ScrollToRow(index);
					mCurrentItem = mNetWorkAdapter.getSelectItem();
					showItemInfo(mCurrentItem);
				}else{
					SetEnabledTrue();
				}
				mNetWorkAdapter.notifyDataSetChanged();
				
			}
		}
		
		@Override
		public void onClickNo() {
		}

		@Override
		public void onClickOK() {

		}
	};

	private OnClickMessageListener confirmExitListener = new OnClickMessageListener() {
		@Override
		public void onClickYes() {
			dispose();
			finish();
		}

		@Override
		public void onClickNo() {
		}

		@Override
		public void onClickOK() {

		}
	};
	
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);
		
		
	}
	
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
		
		switch (what) {
		case R.id.btn_ok:
			mNetworkSettingLst = mNetService.FindAll();
			if (mNetWorkAdapter == null){
				mNetWorkAdapter = new NetworkAdapter(this, mNetworkSettingLst);
				lv_netlist.setAdapter(mNetWorkAdapter);
			}else{
				mNetWorkAdapter.setSource(mNetworkSettingLst);
				mNetWorkAdapter.notifyDataSetChanged();
			}
//			showItemInfo(mCurrentItem);
			if(mNetworkSettingLst.size() > 0){
//				int index = mNetworkSettingLst.size() - 1;
				mNetWorkAdapter.ScrollToRow(0);
				mCurrentItem = mNetworkSettingLst.get(0);
				showItemInfo(mCurrentItem,0);
				SetEnabledFalse2();
			}
			break;

		default:
			break;
		}
	}

}